package xcmg.device.web.warehouse;

import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import xcmg.device.dao.mapper.CompanyInfoMapper;
import xcmg.device.infra.AuthCode;
import xcmg.device.infra.BasicController;
import xcmg.device.infra.ErrorCode;
import xcmg.device.infra.exception.CommonBusiExceptions;
import xcmg.device.service.ExternalParamCheckService;
import xcmg.device.service.audit.AbnormalInAuditService;
import xcmg.device.service.crm.util.ActionResultUtil;
import xcmg.device.service.vo.FunctionResult;
import xcmg.device.service.vo.delivery.BusinessOrderAuditParamVO;
import xcmg.device.service.vo.delivery.ManualFinishVO;
import xcmg.device.service.vo.warehouse.AbnormalInAddVO;
import xcmg.device.service.vo.warehouse.AbnormalInVO;
import xcmg.device.service.warehouse.AbnormalInService;
import yb.ecp.fast.infra.annotation.FastMappingInfo;
import yb.ecp.fast.infra.infra.ActionResult;
import yb.ecp.fast.infra.infra.PageCommonVO;
import yb.ecp.fast.infra.infra.SearchCommonVO;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.util.Arrays;

@RestController
@RequestMapping("/abnormalIn")
public class AbnormalInController extends BasicController {
    @Resource
    private AbnormalInService abnormalInService;
    @Resource
    private AbnormalInAuditService abnormalInAuditService;
    @Resource
    private CompanyInfoMapper companyInfoMapper;
    @Resource
    private ExternalParamCheckService externalParamCheckService;

    @RequestMapping(value = "/add",method = RequestMethod.POST)
    @ApiOperation(value = "增加非正常入库记录")
    @FastMappingInfo(needLogin = true,code = AuthCode.StockIn.UNUSUAL_IN_ADD)
    public ActionResult warehouse(@RequestBody AbnormalInAddVO abnormalInAddVO)throws Exception{
        if(null == abnormalInAddVO){
            return actionResult(ErrorCode.IllegalArument);
        }

        ErrorCode errorCode = abnormalInService.add(abnormalInAddVO, getUserId(), getOrgId(), false);
        return actionResult(errorCode);
    }

    @RequestMapping(value = "/update",method = RequestMethod.POST)
    @ApiOperation(value = "更新非正常入库记录")
    @FastMappingInfo(needLogin = true,code = AuthCode.StockIn.UNUSUAL_IN_EDIT)
    public ActionResult update(@RequestBody AbnormalInAddVO abnormalInAddVO)throws Exception{
        if(null == abnormalInAddVO){
            return actionResult(ErrorCode.IllegalArument);
        }
        try{
            ErrorCode errorCode = abnormalInService.update(abnormalInAddVO, getOrgId());
            return actionResult(errorCode);
        }catch (Exception e){
            return new ActionResult(ErrorCode.Failure.getCode(), e.getMessage());
        }
    }

    @RequestMapping(value = "/remove",method = RequestMethod.POST)
    @ApiOperation("非正常入库记录删除")
    @FastMappingInfo(needLogin = true,code = AuthCode.StockIn.UNUSUAL_IN_DEL)
    public ActionResult remove(@RequestBody String[] ids)throws Exception{
        if(ids==null||ids.length==0){
            return actionResult(ErrorCode.IllegalArument);
        }
        return actionResult(abnormalInService.delete(Arrays.asList(ids), getOrgId()));
    }

    @RequestMapping(value = "/item",method = RequestMethod.GET)
    @ApiOperation(value = "查找单条记录详情")
    @FastMappingInfo(needLogin = true)
    public ActionResult item(String id)throws Exception{
        return actionValueResult(abnormalInService.findByPK(id, "id", getOrgId()));
    }

    @RequestMapping(value = "/itemByNo",method = RequestMethod.GET)
    @ApiOperation(value = "查找单条记录详情")
    @FastMappingInfo(needLogin = true)
    public ActionResult itemByNo(String abnormalNo)throws Exception{
        return actionValueResult(abnormalInService.findByPK(abnormalNo, "abnormalNo", getOrgId()));
    }

    @RequestMapping(value = "/list",method = RequestMethod.POST)
    @ApiOperation("查询非正常入库记录列表")
    @FastMappingInfo(needLogin = true)
    public ActionResult list(@RequestBody SearchCommonVO<AbnormalInVO> condition)throws Exception{
        AbnormalInVO abnormalInVO =condition.getFilters();
        if(abnormalInVO == null){
            abnormalInVO = new AbnormalInVO();
        }
        abnormalInVO.setOrgId(getOrgId());
        condition.setFilters(abnormalInVO);
        PageCommonVO pageCommonVO= abnormalInService.list(condition);
        return actionValueResult(pageCommonVO.getPageInfo());
    }

    @RequestMapping(value = "/export",method = RequestMethod.POST)
    @ApiOperation("导出非正常入库记录列表")
    @FastMappingInfo(needLogin = true,code = AuthCode.StockIn.UNUSUAL_IN_EXPORT)
    public void export( String[] ids)throws Exception {
        abnormalInService.export(Arrays.asList(ids));
    }

    @RequestMapping(value = "/exportAll",method = RequestMethod.POST)
    @ApiOperation("导出全部非正常入库记录列表")
    @FastMappingInfo(needLogin = true,code = AuthCode.StockIn.UNUSUAL_IN_EXPORT)
    public void exportAll(AbnormalInVO condition)throws Exception {
        condition.setOrgId(getOrgId());
        abnormalInService.exportAll(condition);
    }

    @ResponseBody
    @RequestMapping(value = "/import", method = RequestMethod.POST)
    @ApiOperation("零件批量导入")
    @FastMappingInfo(needLogin = true)
    public ActionResult importExcel(HttpServletRequest request) throws Exception{
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile file = multipartRequest.getFile(multipartRequest.getFileNames().next());
        String fileName = file.getOriginalFilename();
        String supplierOrgId = request.getParameter("supplierOrgId");
        if (supplierOrgId == null || supplierOrgId.trim().isEmpty()) {
            throw new CommonBusiExceptions("入参不正确，请先选择供货商");
        }
        FunctionResult<String> result=new FunctionResult<>();
        if (!fileName.trim().endsWith(".xls")) {
            result.setCode(ErrorCode.ImportExcelEndWithXLS);
        } else {
            InputStream in = file.getInputStream();
            result= abnormalInService.importExcel(in,  getOrgId(), supplierOrgId);
        }
        return actionResult(result.getCode(), result.getValue());
    }

    @RequestMapping(value = "/download",method = RequestMethod.POST)
    @ApiOperation("下载零件批量导入模板")
    @FastMappingInfo(needLogin = true)
    public void download() throws Exception {
        abnormalInService.download();
    }

    @RequestMapping(value = "/manualFinish", method = RequestMethod.POST)
    @ApiOperation("手动完成单据")
    public ActionResult manualFinish(@RequestBody ManualFinishVO manualFinishVO) throws Exception
    {
        return actionResult(abnormalInService.manualFinish(manualFinishVO.getBillNo(), manualFinishVO.getMaterialsNo(), getOrgId()));
    }

//    /**
//     * 对外提供添加接口
//     *
//     * @param model
//     * @return
//     * @throws Exception
//     */
//    @RequestMapping(value = "/addAbnormalIn", method = RequestMethod.POST)
//    public ActionResult addAbnormalIn(@RequestBody AbnormalInAddVO model) throws Exception {
//        LogHelper.monitor("addAbnormalIn接口入参：" + model.toString());
//        ActionResult result;
//        CompanyInfoDO companyInfoDO = companyInfoMapper.itemBySap(model.getHeaderInfo().getSapCode());
//        Assert.notNull(companyInfoDO,"companyInfoDO is null.");
//        try {
//            externalParamCheckService.checkParam(fillNeedCheckParan(model));
//            result = abnormalInService.add4CRM(model, model.getHeaderInfo().getUserId(), companyInfoDO.getOrgId(), true);
//        } catch (Exception e) {
//            return actionResult(ErrorCode.Failure, e.getMessage());
//        }
//        return result;
//    }
//
//    /**
//     * 对外提供添加接口(安全校验)
//     *
//     * @param model
//     * @return
//     * @throws Exception
//     */
//    @ExternalApiRequest
//    @RequestMapping(value = "/addAbnormalInBySec", method = RequestMethod.POST)
//    public ActionResult addAbnormalInBySec(@RequestBody AbnormalInAddVO model) throws Exception {
//        LogHelper.monitor("addAbnormalIn接口入参：" + model.toString());
//        ActionResult result;
//        CompanyInfoDO companyInfoDO = companyInfoMapper.itemBySap(model.getHeaderInfo().getSapCode());
//        Assert.notNull(companyInfoDO,"companyInfoDO is null.");
//        try {
//            externalParamCheckService.checkParam(fillNeedCheckParan(model));
//            result = abnormalInService.add4CRM(model, model.getHeaderInfo().getUserId(), companyInfoDO.getOrgId(), true);
//        } catch (Exception e) {
//            return actionResult(ErrorCode.Failure, e.getMessage());
//        }
//        return result;
//    }
//
//    private ExternalParamCheckVO fillNeedCheckParan(AbnormalInAddVO model) throws Exception {
//        ExternalParamCheckVO param = new  ExternalParamCheckVO();
//        if (CollectionUtils.isEmpty(model.getDetailList())) {
//            throw new Exception("缺少零件信息");
//        }
//        List<String> materialsNos = new ArrayList<>();
//        for (AbnormalInDetailVO detailVO : model.getDetailList()) {
//            materialsNos.add(detailVO.getMaterialsNo());
//        }
//        param.setMaterialsNos(materialsNos);
//        AbnormalInVO abnormalIn = model.getHeaderInfo();
//        param.setSapCode(abnormalIn.getSapCode());
//        param.setInArea(abnormalIn.getInArea());
//        param.setInLocation(abnormalIn.getInLocation());
//        param.setAbnormalInNo(abnormalIn.getAbnormalNo());
//        param.setTypeId(abnormalIn.getTypeId());
//        return param;
//    }

    /**
     * @Des 其它入库单审核通过
     * @Date 2021/4/15 9:35
     * @Author wangzhaoyu
     * @Param [param]
     * @Return yb.ecp.fast.infra.infra.ActionResult
     */
    @FastMappingInfo(needLogin = true)
    @RequestMapping(value = "/auditPass" , method = RequestMethod.POST)
    public ActionResult auditPass(@RequestBody BusinessOrderAuditParamVO param){
        String userId = getUserId();
        String userName = getUserName();
        try{
            ActionResult auditResult = abnormalInAuditService.audit(param, userId, userName, true);
            return auditResult;
        }catch (Exception e){
            return ActionResultUtil.errorActionResult(ErrorCode.Failure.getCode(),e.getMessage());
        }
    }
    /**
     * @Des 其它入库单审核拒绝
     * @Date 2021/4/15 9:35
     * @Author wangzhaoyu
     * @Param [param]
     * @Return yb.ecp.fast.infra.infra.ActionResult
     */
    @FastMappingInfo(needLogin = true)
    @RequestMapping(value = "/auditReject" , method = RequestMethod.POST)
    public ActionResult auditReject(@RequestBody BusinessOrderAuditParamVO param){
        String userId = getUserId();
        String userName = getUserName();
        try{
            ActionResult actionResult = abnormalInAuditService.audit(param, userId, userName, false);
            return actionResult;
        }catch (Exception e){
            return ActionResultUtil.errorActionResult(ErrorCode.Failure.getCode(),e.getMessage());
        }
    }

    /**
     * @Des 主页面数据看板--其它入库单待审核数据
     * @Date 2021/4/15 9:26
     * @Author wangzhaoyu
     * @Param []
     * @Return yb.ecp.fast.infra.infra.ActionResult
     */
    @RequestMapping(value = "/mainBoardWaitAudit" , method = RequestMethod.GET)
    @FastMappingInfo(needLogin = true)
    public ActionResult mainBoardWaitAudit() throws Exception {
        String orgId = getOrgId();
        //查询当前机构未删除，已提交的待审核数据
        Integer waitDataCount = abnormalInService.countAuditData(orgId);
        return ActionResultUtil.successActionResult(waitDataCount);
    }
}
